package com.itheima.protocol.socketDemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * socket service
 */
public class SocketServer {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(8888);

            while (true){

                Socket socket = serverSocket.accept();
                new Thread(() -> {
                    try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

                        while (true){
                            String clientData = reader.readLine();
                            if(clientData == null){
                                break;
                            }
                            System.out.println("服务端接收过来的数据:"+ clientData);
                            writer.println("Hello world !!!");
                            writer.flush();
                        }
                        writer.close();
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }).start();
            }

        }catch (Exception e){

        }finally {
            if(serverSocket != null){
                serverSocket.close();
            }
        }


    }
}
